package com.health.web.controller.system;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.health.common.core.controller.BaseController;
import com.health.common.core.domain.AjaxResult;
import com.health.common.core.domain.model.RegisterBody;
import com.health.common.utils.StringUtils;
import com.health.framework.web.service.SysRegisterService;
import com.health.system.service.ISysConfigService;
import com.health.healthSys.domain.HealthUsers;
import com.health.healthSys.mapper.HealthUsersMapper;
import com.health.common.core.domain.entity.SysUser;
import com.health.system.service.ISysUserService;
import com.health.system.service.ISysRoleService;
import java.util.Date;

/**
 * 注册验证
 * 
 * @author ruoyi
 */
@RestController
public class SysRegisterController extends BaseController
{
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private HealthUsersMapper healthUsersMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user)
    {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
        {
            return error("当前系统没有开启注册功能！");
        }
        String msg = registerService.register(user);
        if (StringUtils.isEmpty(msg))
        {
            // 获取新注册的系统用户信息
            SysUser sysUser = userService.selectUserByUserName(user.getUsername());
            if (sysUser != null)
            {
                // 创建health_users表数据
                HealthUsers healthUser = new HealthUsers();
                healthUser.setUsername(sysUser.getUserName());
                healthUser.setPasswordHash(sysUser.getPassword());
                healthUser.setEmail(sysUser.getEmail());
                healthUser.setPhone(sysUser.getPhonenumber());
                healthUser.setUserStatus(sysUser.getStatus());
                healthUser.setSysUserId(sysUser.getUserId());
                healthUser.setRoleId(2L); // 设置默认角色ID为2（user角色）
                healthUser.setCreateTime(new Date());
                healthUsersMapper.insertHealthUsers(healthUser);
            }
            return success();
        }
        return error(msg);
    }
}
